package com.gitee.wsl.lang.ubytearray.api

 interface UOutput {

     fun write(b: UByte)

    @OptIn(ExperimentalUnsignedTypes::class)
     fun write(b: UByteArray)

     fun writeUShort(s: UShort) {
        write((s.toUInt() shr 8).toUByte())
        write((s and 0xFFu).toUByte())
    }

     fun writeUInt(v: UInt) {
        for (i in 0..3) {
            write(((v shr ((3 - i) * 8)) and 0xFFu).toUByte())
        }
    }

     fun writeULong(l: ULong) {
        for (i in 0..7) {
            write(((l shr ((7 - i) * 8)) and 0xFFu).toUByte())
        }
    }
}

 fun UOutput.encodeVariableByteInteger(value: UInt): Int {
    var length = 0
    var x = value
    do {
        var encodedByte = x.rem(128u)
        x /= 128u
        if (x > 0u) {
            encodedByte = encodedByte or 128u
        }
        write(encodedByte.toUByte())
        length++
    } while (x > 0u)
    return length
}